package com.toune.blackmusic.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.toune.blackmusic.activity.BaseActivity;
import com.toune.blackmusic.activity.ScanActivity;
import com.toune.blackmusic.database.DBManager;
import com.toune.blackmusic.database.MusicVo;
import com.toune.blackmusic.entity.MusicInfo;
import com.toune.blackmusic.util.ChineseToEnglish;
import com.toune.blackmusic.util.Constant;
import com.toune.blackmusic.util.MyMusicUtil;
import com.toune.blackmusic.util.MyUtil;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxImageTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.view.RxToast;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

import static com.toune.blackmusic.activity.BaseActivity.context;
import static com.toune.blackmusic.activity.ScanActivity.replaseUnKnowe;

public class DownService extends Service {
    private DownloadRequest downloadRequest;

    public DownService() {
        dbManager = DBManager.getInstance(context);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void startDown(MusicVo.DataBean downVo) {
        //下载文件
        //说明一下下面的几个参数
        //1.url
        //2.文件存储路径
        //3.文件名
        //4.断点是否继续
        //5.是否删除旧的
        downloadRequest = NoHttp.createDownloadRequest(downVo.getUrl(),
                MyUtil.getAppMusicPath(),
                downVo.getTitle() + "~" + downVo.getAuthor() + ".mp3",
                true,
                true);
        downloadRequest.setCancelSign(downVo.getLink());//设置停止下载的记号
        down(downVo);
    }

    private int WHAT = 0;

    private void down(final MusicVo.DataBean downVo) {
        check();
        NoHttp.getDownloadQueueInstance().add(WHAT, downloadRequest, new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {
                //下载异常
                RxToast.error("下载异常");
            }

            @Override
            public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
                //开始下载
                //what
                //isResume 是否重新下载
                //rangeSize 已下载文件大小
                //responseHeaders
                //allCount 文件总大小
                //int progress = (int) (rangeSize * 100 / allCount); 下载进度
            }

            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
            }


            @Override
            public void onFinish(int what, String path) {

                File file = new File(path);
                //歌词存到本地
                RxFileTool.write(MyUtil.getAppMusicPath() + RxFileTool.getFileName(file) + ".lrc", downVo.getLrc());
                RxSPTool.putString(context, downVo.getTitle() + downVo.getAuthor(), downVo.getPic());
                String parentPath = file.getParentFile().getPath();
                String name = replaseUnKnowe(downVo.getTitle());
                String singer = replaseUnKnowe(downVo.getAuthor());
                String album = replaseUnKnowe(downVo.getPic());
                path = replaseUnKnowe(path);

                MusicInfo musicInfo = new MusicInfo();

                musicInfo.setName(name);
                musicInfo.setSinger(singer);
                musicInfo.setAlbum(album);
                musicInfo.setPath(path);
                musicInfo.setParentPath(parentPath);
                musicInfo.setPic(downVo.getPic());
                musicInfo.setLrcPath(downVo.getLrc());
                musicInfo.setFirstLetter(ChineseToEnglish.StringToPinyinSpecial(name).toUpperCase().charAt(0) + "");
                scanFile(context, path);
                EventBus.getDefault().post(new ScanMsg("ok"));
                RxToast.success("下载完成");
            }

            @Override
            public void onCancel(int what) {
                //下载取消
                downloadRequest.cancelBySign(downVo.getLink());//通过记号停止下载
            }
        });
    }
    //更新媒体库

    /**
     * 通知媒体库更新文件
     *
     * @param context
     * @param filePath 文件全路径
     */
    public void scanFile(Context context, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        context.sendBroadcast(scanIntent);
    }


    public static DBManager dbManager;

    private void check() {
        // 检查之前的下载状态
        int beforeStatus = downloadRequest.checkBeforeStatus();
        switch (beforeStatus) {
            case DownloadRequest.STATUS_RESTART:
                RxToast.showToast("开始下载");
                break;
            case DownloadRequest.STATUS_RESUME:
                RxToast.showToast("正在下载");
                break;
            case DownloadRequest.STATUS_FINISH:
                RxToast.showToast("下载完成");
                break;
        }
    }
}
